import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Modal, Card, Tabs, Space, Button, Input } from 'antd';
import { connect, history } from 'umi';
import MessageComponents from '../MessageComponents';
import { PictureOutlined, CloseCircleFilled, CloudUploadOutlined } from '@ant-design/icons'
import { backgroundObj } from '@/utils/utils'
import EditModal from './components/editModal';
import aliOssUpload from "@/utils/aliOssUpload";
import './index.less'
const SelectFriend = (props) => {
    const { dispatch, detail = {}, show, timeInit, editType } = props;
    const [visible, setVisible] = useState(false);
    const [list, setList] = useState([]);
    const [total, setTotal] = useState(0);
    const [value, setValue] = useState('');
    const [isInitialLoad, setIsInitialLoad] = useState(true);
    const containerRef = useRef(null);
    const [isAtTop, setIsAtTop] = useState(false);
    const [imageList, setImageList] = useState([])
    const openImagePicker = async () => {
        try {
            const fileHandle = await window.showOpenFilePicker({
                multiple: true, // 设置为 false 表示只能选择一个文件
                types: [
                    {
                        accept: {
                            'image/*': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff', '.svg'],
                            'video/*': ['.mp4']
                        }
                    },

                ]
            });
            const fileList = await Promise.all(fileHandle.map(async val => {
                const file = await val.getFile();
                return file
            }))
            const img = await aliOssUpload(fileList)
            setImageList((e) => ([...e, ...img]))
        } catch (error) {
            console.error(error);
        }
    }
    // 滚动位置调整参考值
    const adjustScrollRef = useRef({
        shouldAdjust: false,
        previousScrollHeight: 0,
        previousScrollTop: 0
    });

    const initTimt = () => {
        if (timeInit.current) {
            clearInterval(timeInit.current)
        }
        timeInit.current = setInterval(val => {
            setList(e => {
                const lastMessage = e.reduce((item, val, index) => {
                    if (index === e.length - 1) {
                        const { createTime } = val
                        return createTime
                    }
                    return item
                }, '')

                fetchInitData(lastMessage)
                return e
            })
        }, 1000)
    }
    // 滚动处理逻辑
    const handleScroll = () => {
        setIsAtTop(isScrollAtTop(containerRef));
    };

    const isScrollAtTop = (containerRef) => {
        return containerRef.current?.scrollTop < 10;
    };
    const submit = () => {

        dispatch({
            type: 'answering/fakeChatUserQa',
            payload: {
                content: JSON.stringify({
                    contentType: 'mix',
                    text: value,
                    images: imageList.toString()
                }),
                userQaId: detail.id
            },
            callback: () => {
                setImageList([])
                setValue('')
            }
        })
    }
    // 滚动位置调整逻辑
    useEffect(() => {
        const container = containerRef.current;
        if (!container) return;

        // 处理历史消息加载后的位置保持
        if (adjustScrollRef.current.shouldAdjust) {
            const { previousScrollHeight, previousScrollTop } = adjustScrollRef.current;
            const delta = container.scrollHeight - previousScrollHeight;
            container.scrollTop = previousScrollTop + delta;
            adjustScrollRef.current.shouldAdjust = false;
        }

        // 首次加载滚动到底部
        if (list.length > 0) {
            container.scrollTop = container.scrollHeight;
            setIsInitialLoad(false);
        }
    }, [list.length, isInitialLoad]);

    // 滚动事件监听
    useEffect(() => {
        const container = containerRef.current;
        if (!container) return;

        container.addEventListener('scroll', handleScroll);
        if (show) {
            initTimt()
        }
        else {
            clearInterval(timeInit.current)
        }
        return () => container.removeEventListener('scroll', handleScroll);
    }, [show]);

    // 获取历史消息
    const fetchData = (lastMessageTime) => {
        const container = containerRef.current;
        if (container) {
            adjustScrollRef.current = {
                shouldAdjust: true,
                previousScrollHeight: container.scrollHeight,
                previousScrollTop: container.scrollTop
            };
        }
        dispatch({
            type: 'answering/fetchUserQaRecord',
            payload: {
                userQaId: detail.id,
                lastMessage: lastMessageTime,
                page: 1,
                limit: 100
            },
            callback: (e, total) => {
                setList(prev => [...e, ...prev]);  // 历史消息添加到前面
                setTotal(total);
            }
        });
    };
    const fetchInitData = (lastMessageTime) => {
        dispatch({
            type: 'answering/fetchListLastUserQaRecord',
            payload: {
                userQaId: detail.id,
                lastMessage: lastMessageTime,
                page: 1,
                limit: 100
            },
            callback: (e, total) => {
                setList(prev => [...prev, ...e,]);  // 历史消息添加到前面
                setTotal(total);
            }
        });
    };
    // 初始化或切换好友时加载
    const fetchDataReload = () => {
        dispatch({
            type: 'answering/fetchUserQaRecord',
            payload: {
                userQaId: detail.id,
                lastMessage: detail.lastMessageTime,
                page: 1,
                limit: 100
            },
            callback: (e, total) => {
                setList([...e]);  // 全新数据
                setTotal(total);
                setIsInitialLoad(true);  // 标记需要初始化滚动
            }
        });
    };

    // 滚动到顶部时加载更多
    useEffect(() => {
        if (isAtTop && list[0]?.messageTime) {
            fetchData(list[0].messageTime);
        }
    }, [isAtTop]);

    // 切换好友时重置
    useEffect(() => {
        if (show) {
            setList([]);
            setTotal(0);
            fetchDataReload();
        }
    }, [show]);
    function assignTypeIndex(list) {
        // 创建一个对象来跟踪每种类型的当前索引
        const typeCounters = {};

        // 遍历列表并为每个元素添加类型索引
        return list.map(item => {
            const type = item.answerUserType;

            // 如果该类型首次出现，初始化计数器为1，否则递增
            if (!(type in typeCounters)) {
                typeCounters[type] = 1;
            } else {
                typeCounters[type] += 1;
            }

            // 返回新对象（不修改原对象）并添加类型索引
            return {
                ...item,
                askIndex: typeCounters[type]
            };
        });
    }
    function isImageFile(path) {
        // 提取文件扩展名（不区分大小写）
        const extension = path.split('.').pop().toLowerCase();

        // 常见图片扩展名列表
        const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];

        return imageExtensions.includes(extension);
    }
    // 渲染逻辑
    if (!show) {
        return <div style={{ width: '100%', height: 700, border: '1px solid rgba(140, 140, 140, 0.35)' }}>
            <Empty></Empty>
        </div>
    } else {
        const { askUsername } = detail
        return <div className='SelectFriend_box' style={{ width: '100%', height: 756, border: '1px solid rgba(140, 140, 140, 0.35)' }}>
            <div ref={containerRef} style={{ height: 600, overflowY: 'auto' }} className='SelectFriend_list'>
                {assignTypeIndex(list).map((val) => {
                    return <MessageComponents data={val}></MessageComponents>
                })}
            </div>
            <div style={{ height: 64, padding: '0 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
                {imageList.map(item => {
                    if (!isImageFile(item)) {
                        return <div onClick={() => { window.open(item) }} className="AnsweringAi_file font_hide">
                            {item}
                            <CloseCircleFilled onClick={(e) => {
                                e.stopPropagation()
                                setImageList(e => {
                                    return e.filter(val => { return val !== item })
                                })
                            }} className="AnsweringAi_textArea_close"></CloseCircleFilled>
                        </div>
                    }
                    return <div style={backgroundObj(item)} className="AnsweringAi_textArea_image">
                        <CloseCircleFilled onClick={() => {
                            setImageList(e => {
                                return e.filter(val => { return val !== item })
                            })
                        }} className="AnsweringAi_textArea_close"></CloseCircleFilled>
                    </div>
                })}
            </div>
            <div className='SelectFriend_send'>
                <div style={{ position: "relative" }}>
                    <Input.TextArea placeholder='请详细查看客户问题描述，精准回答疑问~' disabled={editType === '0'} onChange={(e) => setValue(e.target.value)} value={value} style={{ height: '88px' }} />
                    <div onClick={() => { openImagePicker() }} style={{
                        padding: '12px',
                        cursor: 'pointer',
                        position: 'absolute',
                        right: 96,
                        bottom: -8,
                        fontSize: 32
                    }}>
                        <CloudUploadOutlined style={{ color: '#1677ff' }} size={64}></CloudUploadOutlined>
                    </div>
                    <Button disabled={editType === '0'} onClick={() => {
                        submit()
                    }} style={{
                        position: 'absolute',
                        right: 24,
                        bottom: 12
                    }} type='primary'>发送</Button>
                </div>

            </div>
        </div>
    }




};
const MessageModal = (props) => {
    const { visible = {}, onClose, onOk, dispatch } = props;
    const { show = false, detail = {}, title, editType = 'detail' } = visible;
    const [editVisible, setEditVisible] = useState(false)
    const timeInit = useRef(null)
    const modalProps = {
        title: editType === 'detail' ? title : <Space>
            <div>
                {title}-
            </div>
            <div>
                用户剩余提问 {detail.remainAskAmount}/ {detail.askAmount}次
            </div>
        </Space>,
        width: 1200,
        visible: typeof visible === 'boolean' ? visible : show,
        zIndex: 1001,
        okText: '确认',
        destroyOnClose: true,
        footer: null
    };
    const memo = useMemo(() => {
        return (
            <Modal
                {...modalProps}
                onCancel={onClose}
                onOk={() => {
                    onClose();
                }}
            >
                <SelectFriend editType={editType === 'detail' ? '0' : '1'} timeInit={timeInit} dispatch={dispatch} show={show} detail={detail}></SelectFriend>
                <EditModal visible={editVisible} onClose={() => {
                    setEditVisible(false)
                }}></EditModal>
            </Modal>
        )
    }, [visible, editVisible])
    return memo
}
export default connect(({ answering, loading }) => ({
    loading: loading.effects['answering/fetchListLastUserQaRecord'],
}))(MessageModal);

